﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using TestBAT;
using System.Diagnostics;
using System.IO;
using System.Configuration;
using System.Text.RegularExpressions;
using XTCoverInstrumentor.RepRef; 

namespace XTCoverInstrumentor
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        const string _testContainer = "Test container field can not be empty";
        const string _runConfig = "Run config field can not be empty";
        const string _resultFile = "Result file field can not be empty";
        const string _userScheme = "User defined scheme field can not be empty";
        const string _FileExtPath = "File extraction path field can not be emtpy";
        const string _NUnitEXEpath = "NUnit EXE path field can not be empty";
        const string _NUnitAssemblyName = "Assembly name field can not be empty";
        const string _NUnitTestContainer = "NUnit test container field can not be empty";
        const string _NUnitResultFile = "Result file field can not be empty";
        const string _NUnitFileExtPath = "File extractionn path can not be empty";
        const string _NUnitDLLLocation = "DLL Location field can not be empty";

        public Window1()
        {
            InitializeComponent();

            //MSTest section validation
            SetTextBoxProperties(txtTestContainer, false, _testContainer);
            SetTextBoxProperties(txtRunConfig, false, _runConfig);
            SetTextBoxProperties(txtResultsFile, false, _resultFile);
            SetTextBoxProperties(txtConfigName, false,_userScheme);
            SetTextBoxProperties(txtFileExtractionPath, false, _FileExtPath);

            //NUnit section validation
            SetTextBoxProperties(txtNUnitEXEPath, false, _NUnitEXEpath);
            SetTextBoxProperties(txtAssName, false,_NUnitAssemblyName);
            SetTextBoxProperties(txtNunitTestContainer, false, _NUnitTestContainer);
            SetTextBoxProperties(txtResultFile, false,_NUnitResultFile);
            SetTextBoxProperties(txtFileExtPath, false, _NUnitFileExtPath);
            SetTextBoxProperties(txtDLLlocation, false, _NUnitDLLLocation);
        }


        private void SetTextBoxProperties(TextBox ctrl, bool valid, string tip)
        {
            if (valid)
            {
                ctrl.BorderBrush = (Brush)TryFindResource("DefaultBorderBrush");
                ctrl.ToolTip = null;
            }
            else
            {
                ctrl.BorderBrush = (Brush)TryFindResource("FaultyBorderBrush");
                ctrl.ToolTip = tip;
            }
        }



        private void btnSubmit_Click(object sender, RoutedEventArgs e)
        {
            bool valid = false;
            string message = string.Empty;
            valid = txtTestContainer.isTextRequired(); 
            if (!valid)
            {
                message = "Test container field can not be empty !" + "\r\n";
            }
            valid = txtRunConfig.isTextRequired();
            if (!valid)
            {
                message = message + "Run config field can not be empty !" + "\r\n";
            }
            valid = txtResultsFile.isTextRequired();
            if (!valid)
            {
                message = message + "Result file field can not be emtpy !" + "\r\n";
            }
            valid = txtConfigName.isTextRequired();
            if (!valid)
            {
                message = message + "User defined scheme field can not be empty" + "\r\n";
            }
            valid = txtFileExtractionPath.isTextRequired(); 
            if (!valid)
            {
                message = message + "File extraction path field can not be empty" + "\r\n";
            }

            if (!string.IsNullOrEmpty(message))
            {
                MessageBox.Show(message);
            }
            else
            {
                TestBATExecution tb = new TestBATExecution();
                string strAppPath = string.Empty;
                string strXMLpath = tb.ExecuteCoverage(txtTestContainer.Text.Trim(), txtRunConfig.Text.Trim(), txtResultsFile.Text.Trim(), txtConfigName.Text.Trim(), txtFileExtractionPath.Text.Trim());
                if (!string.IsNullOrEmpty(strXMLpath))
                {
                    //if (strXMLpath)
                    //{
                    //Session["RptXMLPath"] = strXMLpath;
                    //strAppPath = ConfigurationManager.AppSettings["InitialPage"];
                    strAppPath = ConfigurationManager.AppSettings.Get("URLScheme").ToString() + "coveragereport/ContentPages/Dashboard.aspx" + "?rptLink=" + strXMLpath;
                    if (!string.IsNullOrEmpty(strAppPath))
                    {
                        Process.Start("IExplore.exe", strAppPath);
                    }
                    //}

                }
                //else
                //{
                //    ClientScript.RegisterStartupScript(GetType(), "myalert", "<script>alert('Coverage process is not succeeded. You may need to check user-defined scheme of your testrunconfig or provide the same scheme name in user-defined scheme name parameter');</script>");
                //}
            }

            
            
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //string foldPath = @"c:\temp";
            string foldPath = ConfigurationManager.AppSettings.Get("SourceDir");
            //foreach (string strPath in ConfigurationManager.AppSettings)
            //{
            //    foldPath = ConfigurationManager.AppSettings["SourceDir"];
            //}

            if (ValidFilePath(foldPath))
            {
                if (Directory.Exists(foldPath))
                {
                    //TestBATExecution tbat = new TestBATExecution();
                    //List<FileNames> fNames = tbat.GetCoverageSource(foldPath);
                    //cmbSource.Items.Insert(0, "Select coverage source");
                    //foreach (FileNames fl in fNames)
                    //{
                    //    cmbSource.Items.Add(fl.FileName);
                    //}
                    //cmbSource.SelectedIndex = 0;
                    RepRef.IsimpleWcfClient myClient = new IsimpleWcfClient();
                    RepRef.FileNames[] fNames = myClient.GetSourceFiles(foldPath);
                    cmbSource.Items.Insert(0, "Select coverage source");
                    foreach (RepRef.FileNames f1 in fNames)
                    {
                        cmbSource.Items.Add(f1.FileName);
                    }
                    cmbSource.SelectedIndex = 0;
                }
            }
            else
            {
                MessageBox.Show("Please check the source directory path");
            }

            cmbTestType.Items.Add("MSTest");
            cmbTestType.Items.Add("NUnit");
            cmbTestType.Items.Insert(0, "Select Test Type");
            cmbTestType.SelectedIndex = 0;
        }

        public bool ValidFilePath(string path)
        {
            String pattern = @"^(([a-zA-Z]\:)|(\\))(\\{1}|((\\{1})[^\\]([^/:*?<>""|]*))+)$";
            Regex reg = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            return reg.IsMatch(path);
        }

        private void cmbSource_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string strPath = string.Empty;
            if (cmbSource.SelectedIndex > 0)
            {
                strPath = ConfigurationManager.AppSettings.Get("SourceDir").ToString() + cmbSource.SelectedItem.ToString();
                int intItem = cmbSource.SelectedIndex;
                string appPath = ConfigurationManager.AppSettings.Get("URLScheme").ToString() + "CoverageReport/ContentPages/Dashboard.aspx?" + "rptLink=" + strPath;
                //if (cmbSource.SelectedIndex != 0)
                //{
                //    Session["RptXMLPath"] = ConfigurationManager.AppSettings["SourceDir"] + cmbSource.SelectedItem.ToString();

                //    if (intItem == 1)
                //    {
                //        Session["ProjName"] = "Composite Application Library";
                //    }
                //    else if (intItem == 2 || intItem == 3 || intItem == 4 || intItem == 6)
                //    {
                //        Session["ProjName"] = "Sample Application";
                //    }
                //    else if (intItem == 5 || intItem == 7)
                //    {
                //        Session["ProjName"] = "Model View Controller";
                //    }

                //    strPath = ConfigurationManager.AppSettings["InitialPage"];
                //    Server.Transfer(strPath);
                //}
                Process.Start("IExplore.exe", appPath);
            }
            
        }

        private void imgTestContainer_MouseDown(object sender, MouseButtonEventArgs e)
        {
            MessageBoxButton btn = MessageBoxButton.OK;
            MessageBoxImage img = MessageBoxImage.Information;
            MessageBox.Show("Provide valid test assembly path ending with DLL extension. You can provide multiple test assembly path by separating using semicolon", "Test assembly path", btn, img);
        }

        private void imgTestConfig_MouseDown(object sender, MouseButtonEventArgs e)
        {
            MessageBoxButton btn = MessageBoxButton.OK;
            MessageBoxImage img = MessageBoxImage.Information;
            MessageBox.Show("Provide valid path ending with TESTRUNCONFIG extension", "Test Configuration", btn, img);
        }

        private void imgTestOutput_MouseDown(object sender, MouseButtonEventArgs e)
        {
            MessageBoxButton btn = MessageBoxButton.OK;
            MessageBoxImage img = MessageBoxImage.Information;
            MessageBox.Show("Provide valid path ending with TRX extension", "Result file", btn, img);
        }

        private void imgScheme_MouseDown(object sender, MouseButtonEventArgs e)
        {
            MessageBoxButton btn = MessageBoxButton.OK;
            MessageBoxImage img = MessageBoxImage.Information;
            MessageBox.Show("Provide the same scheme name configured in your testrunconfig file", "User Defined Scheme", btn, img);
        }

        private void imgFilePath_MouseDown(object sender, MouseButtonEventArgs e)
        {
            MessageBoxButton btn = MessageBoxButton.OK;
            MessageBoxImage img = MessageBoxImage.Information;
            MessageBox.Show("Provide a valid path for placing MSBuild operation results", "File Extraction Path", btn, img);
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            txtTestContainer.Text = string.Empty;
            txtRunConfig.Text = string.Empty;
            txtResultsFile.Text = string.Empty;
            txtConfigName.Text = string.Empty;
            txtFileExtractionPath.Text = string.Empty;
            txtTestContainer.Focus();
        }

        private void cmbTestType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbTestType.SelectedIndex > 0)
            {
                if (cmbTestType.SelectedIndex == 1)
                {
                    grdMstest.Visibility = Visibility.Visible;
                    grdNUnit.Visibility = Visibility.Collapsed; 
                }
                else if (cmbTestType.SelectedIndex == 2)
                {
                    grdMstest.Visibility = Visibility.Collapsed;
                    grdNUnit.Visibility = Visibility.Visible; 
                }
            }
        }

        private void btnNUnitSubmit_Click(object sender, RoutedEventArgs e)
        {
            bool valid = false;
            string message = string.Empty;
            valid = txtNUnitEXEPath.isTextRequired();
            if (!valid)
            {
                message = "NUnit EXE path field can not be empty !" + "\r\n";
            }
            valid = txtAssName.isTextRequired();
            if (!valid)
            {
                message = message + "Assembly list field can not be empty !" + "\r\n";
            }
            valid = txtNunitTestContainer.isTextRequired();
            if (!valid)
            {
                message = message + "NUnit test container field can not be empty !" + "\r\n";
            }
            valid = txtResultFile.isTextRequired();
            if (!valid)
            {
                message = message + "Result file field can not be empty !" + "\r\n";
            }
            valid = txtFileExtPath.isTextRequired();
            if (!valid)
            {
                message = message + "File extraction path field can not be empty !" + "\r\n";
            }
            valid = txtDLLlocation.isTextRequired();
            if (!valid)
            {
                message = message + "DLL location field can not be empty !" + "\r\n";
            }

            if (!string.IsNullOrEmpty(message))
            {
                MessageBox.Show(message);
            }
            else
            {
                TestBATExecution tb = new TestBATExecution();
                string strAppPath = string.Empty;
                string strXMLpath = tb.ExecuteNunitCoverage(txtNUnitEXEPath.Text, txtNunitTestContainer.Text, txtAssName.Text, txtResultFile.Text, txtFileExtPath.Text, txtDLLlocation.Text);
                if (!string.IsNullOrEmpty(strXMLpath))
                {
                    //if (strXMLpath)
                    //{
                    //Session["RptXMLPath"] = strXMLpath;
                    //strAppPath = ConfigurationManager.AppSettings["InitialPage"];
                    strAppPath = ConfigurationManager.AppSettings.Get("URLScheme").ToString() + "coveragereport/ContentPages/Dashboard.aspx" + "?rptLink=" + strXMLpath;
                    if (!string.IsNullOrEmpty(strAppPath))
                    {
                        Process.Start("IExplore.exe", strAppPath);
                    }
                    //}

                }
                //else
                //{
                //    ClientScript.RegisterStartupScript(GetType(), "myalert", "<script>alert('Coverage process is not succeeded. You may need to check user-defined scheme of your testrunconfig or provide the same scheme name in user-defined scheme name parameter');</script>");
                //}
            }
        }

        private void btnNUnitCancel_Click(object sender, RoutedEventArgs e)
        {
            txtNUnitEXEPath.Text = string.Empty;
            txtAssName.Text = string.Empty;
            txtNunitTestContainer.Text = string.Empty;
            txtResultFile.Text = string.Empty;
            txtFileExtPath.Text = string.Empty;
            txtDLLlocation.Text = string.Empty;
            txtNUnitEXEPath.Focus();
        }

        private void imgNUnitExePath_MouseDown(object sender, MouseButtonEventArgs e)
        {
            MessageBoxButton btn = MessageBoxButton.OK;
            MessageBoxImage img = MessageBoxImage.Information;
            MessageBox.Show("Provide NUnit EXE full path", "NUnit EXE path", btn, img);
        }

        private void imgFileExtPath_MouseDown(object sender, MouseButtonEventArgs e)
        {
            MessageBoxButton btn = MessageBoxButton.OK;
            MessageBoxImage img = MessageBoxImage.Information;
            MessageBox.Show("Provide a valid path for extracting the output file", "File Extraction Path", btn, img);
        }

        private void imgResultFile_MouseDown(object sender, MouseButtonEventArgs e)
        {
            MessageBoxButton btn = MessageBoxButton.OK;
            MessageBoxImage img = MessageBoxImage.Information;
            MessageBox.Show("Provide a valid name for the output file with .coverage extension", "Result File", btn, img);
        }

        private void imgNUnitTestContainer_MouseDown(object sender, MouseButtonEventArgs e)
        {
            MessageBoxButton btn = MessageBoxButton.OK;
            MessageBoxImage img = MessageBoxImage.Information;
            MessageBox.Show("Provide multiple test assemblies path using semicolon as separator", "Test Container Path", btn, img);
        }

        private void imgAssName_MouseDown(object sender, MouseButtonEventArgs e)
        {
            MessageBoxButton btn = MessageBoxButton.OK;
            MessageBoxImage img = MessageBoxImage.Information;
            MessageBox.Show("Provide assemblies name list using semicolon as separator", "Assembly name", btn, img);
        }

        private void imgDLLlocation_MouseDown(object sender, MouseButtonEventArgs e)
        {
            MessageBoxButton btn = MessageBoxButton.OK;
            MessageBoxImage img = MessageBoxImage.Information;
            MessageBox.Show("Provide DLL location", "DLL Location", btn, img);
        }

        private void txtTestContainer_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox box = sender as TextBox;
            if (box != null)
            {
                SetTextBoxProperties(box, box.isTextRequired(), _testContainer);
            }
        }

        private void txtRunConfig_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox box = sender as TextBox;
            if (box != null)
            {
                SetTextBoxProperties(box, box.isTextRequired(), _runConfig);
            }
        }

        private void txtResultsFile_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox box = sender as TextBox;
            if (box != null)
            {
                SetTextBoxProperties(box, box.isTextRequired(), _resultFile);
            }
        }

        private void txtConfigName_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox box = sender as TextBox;
            if (box != null)
            {
                SetTextBoxProperties(box, box.isTextRequired(), _userScheme);
            }
        }

        private void txtFileExtractionPath_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox box = sender as TextBox;
            if (box != null)
            {
                SetTextBoxProperties(box, box.isTextRequired(),_FileExtPath);
            }
        }

        private void txtNUnitEXEPath_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox box = sender as TextBox;
            if (box != null)
            {
                SetTextBoxProperties(box, box.isTextRequired(), _NUnitEXEpath);
            }
        }

        private void txtAssName_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox box = sender as TextBox;
            if (box != null)
            {
                SetTextBoxProperties(box, box.isTextRequired(), _NUnitAssemblyName);
            }
        }

        private void txtNunitTestContainer_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox box = sender as TextBox;
            if (box != null)
            {
                SetTextBoxProperties(box, box.isTextRequired(), _NUnitTestContainer);
            }
        }

        private void txtResultFile_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox box = sender as TextBox;
            if (box != null)
            {
                SetTextBoxProperties(box, box.isTextRequired(), _NUnitResultFile);
            }
        }

        private void txtFileExtPath_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox box = sender as TextBox;
            if (box != null)
            {
                SetTextBoxProperties(box, box.isTextRequired(), _NUnitFileExtPath);
            }
        }

        private void txtDLLlocation_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox box = sender as TextBox;
            if (box != null)
            {
                SetTextBoxProperties(box, box.isTextRequired(), _NUnitDLLLocation);
            }
        }

        
    }

    public static class CustomExtensions
    {
        public static bool isTextRequired(this TextBox obj)
        {
            if (obj.Text.Length > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
